//模拟数据库
let data_list = [{
        "id": 1,
        "name": "Soul",
        "price": 18
    },
    {
        "id": 2,
        "name": "呀",
        "price": 188
    },
    {
        "id": 3,
        "name": "人走茶凉",
        "price": 188
    },
    {
        "id": 4,
        "name": "哈",
        "price": 188
    }
]

//展示数据（可能是查找也可能是展示所有数据）
let fn_data = async(ctx, next) => {
    ctx.body = data_list;
    let keyword = ctx.request.query.keyword
    if (keyword) {
        ctx.body = data_list.filter(item => {
            return item.id == keyword || item.name == keyword || item.price == keyword
        })
    } else {
        ctx.body = data_list;
    }
}

//添加数据
let fn_addorEndit = async(ctx, next) => {
    let obj = ctx.request.body;
    //判断save引发的请求到底是新增还是编辑
    if (!obj.id) {
        //已存在相同名称的不可以添加  
        let temp = data_list.filter(item => {
            return item.name === obj.name
        })
        if (temp.length === 0) {
            obj.id = data_list.length + 1 //使id自增
            data_list.push(obj) //把新增数据加入数组
        }
    } else {
        data_list.forEach(item => {
            if (item.id == obj.id) {
                item['name'] = obj.name;
                item['price'] = obj.price;
            }
        })
    }
    ctx.body = 200; //反正不是渲染，最后都得重新加载，我保证数据库已经彻彻底底改变即可
}

//得到修改的数据
let fn_endit = async(ctx, next) => {
    let tempdata = data_list.filter(item => {
        return item.id == ctx.request.params.id
    })
    ctx.body = tempdata
}

//删除数据
let fn_delete = async(ctx, next) => {
    let id = ctx.request.params.id
    data_list = data_list.filter(item => {
        if (item.id != id) {
            return true
        }
    })
    ctx.body = data_list
}

module.exports = {
    //展示数据或查找
    'get /produce': fn_data,
    //新增
    'post /produce': fn_addorEndit,
    //修改
    'get /produce/:id': fn_endit,
    'put /produce': fn_addorEndit,
    //删除  
    'delete /produce/:id': fn_delete
}